import logging
import os
import socket

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.redis import RedisInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

logger = logging.getLogger(__name__)


def init_tracer(app, trace_host):
    # Service name is required for most backends
    resource = Resource(
        attributes={
            SERVICE_NAME: os.getenv('SERVICE_NAME', 'UNKNOWN_SERVICE'),
        }
    )
    provider = TracerProvider(resource=resource)

    try:
        socket.getaddrinfo(trace_host, None)

        processor = BatchSpanProcessor(
            OTLPSpanExporter(endpoint=f'http://{trace_host}', insecure=True)
        )
        provider.add_span_processor(processor)

        trace.set_tracer_provider(provider)

        FlaskInstrumentor().instrument_app(app)
        SQLAlchemyInstrumentor().instrument(enable_commenters=True)
        RequestsInstrumentor().instrument()
        RedisInstrumentor().instrument()
    except Exception as e:
        logger.warning(
            f'init_tracer failed, reason: resolve host({trace_host}) exception: {repr(e)}'
        )
